package com.example.healkep;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.healkep.utils.Captcha.Captcha;

import org.json.JSONObject;

import java.util.Objects;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CaptchaRActivity extends AppCompatActivity {
    public static boolean result;
    private Captcha captcha;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_captchar);
        captcha = findViewById(R.id.captCha2);
        Button btnMode = findViewById(R.id.btn_mode);
        Button refresh = findViewById(R.id.refreshr);

        final Bundle bundle = getIntent().getExtras();
        String json = bundle.getString("json");
        String username = bundle.getString("username");

        btnMode.setOnClickListener(v -> {
            if (captcha.getMode() == Captcha.MODE_BAR) {
                captcha.setMode(Captcha.MODE_NONBAR);
                btnMode.setText("滑动条模式");
            } else {
                captcha.setMode(Captcha.MODE_BAR);
                btnMode.setText("无滑动条模式");
            }
        });

        refresh.setOnClickListener(v -> {
            Random r = new Random();
            int id = r.nextInt(7) + 1;
            switch (id){
                case 1:captcha.setBitmap(R.drawable.captcha1);break;
                case 2:captcha.setBitmap(R.drawable.captcha2);break;
                case 3:captcha.setBitmap(R.drawable.captcha3);break;
                case 4:captcha.setBitmap(R.drawable.captcha4);break;
                case 5:captcha.setBitmap(R.drawable.captcha5);break;
                case 6:captcha.setBitmap(R.drawable.captcha6);break;
                case 7:captcha.setBitmap(R.drawable.captcha7);break;
                default:break;
            }
        });

        captcha.setCaptchaListener(new Captcha.CaptchaListener() {
            @Override
            public String onAccess(long time) {
                Toast.makeText(CaptchaRActivity.this, "验证成功", Toast.LENGTH_SHORT).show();
                LoginActivity.setUser(username);
                new Thread(() -> {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(LoginActivity.url + "/login/loginuser")
                                .post(RequestBody.create(MediaType.parse("application/json"), json))
                                .build();
                        Response response = client.newCall(request).execute();
                        String result = Objects.requireNonNull(response.body()).string();
                        JSONObject object = new JSONObject(result);
                        String resultx = object.getString("exist");
                        if (resultx.equals("false")) {//用户名不重复
                            try {
                                OkHttpClient client2 = new OkHttpClient();
                                Request request2 = new Request.Builder()
                                        .url(LoginActivity.url + "/login/register")
                                        .post(RequestBody.create(MediaType.parse("application/json"), json))
                                        .build();
                                Response response2 = client2.newCall(request2).execute();
                                try {
                                    OkHttpClient client3 = new OkHttpClient();
                                    Request request3 = new Request.Builder()
                                            .url(LoginActivity.url + "/login/login")
                                            .post(RequestBody.create(MediaType.parse("application/json"), json))
                                            .build();
                                    Response response3 = client3.newCall(request3).execute();//借助登录查询判断注册是否成功
                                    String responseData = Objects.requireNonNull(response3.body()).string();
                                    JSONObject jsonobject = new JSONObject(responseData);
                                    String result3 = jsonobject.getString("register");
                                    if (result3.equals("true"))//有此用户
                                    {
                                        runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "注册成功", Toast.LENGTH_SHORT).show());
                                        LoginActivity.setUser(username);
                                        Intent intent = new Intent();
                                        intent.setClass(CaptchaRActivity.this, NewInformationActivity.class);
                                        startActivity(intent);
                                    } else {//没有此用户
                                        runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "注册失败", Toast.LENGTH_SHORT).show());
                                        Intent intent = new Intent();
                                        intent.setClass(CaptchaRActivity.this, LoginActivity.class);
                                        startActivity(intent);
                                    }
                                    CaptchaRActivity.this.finish();
                                } catch (Exception e) {
                                    runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "连接失败!", Toast.LENGTH_SHORT).show());
                                }
                            } catch (Exception e) {
                                runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "连接失败？", Toast.LENGTH_SHORT).show());
                                Intent intent = new Intent();
                                intent.setClass(CaptchaRActivity.this, LoginActivity.class);
                                startActivity(intent);
                                CaptchaRActivity.this.finish();
                            }
                        } else if (resultx.equals("true")) {//用户名重复
                            runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "用户名重复,注册失败", Toast.LENGTH_SHORT).show());
                            Intent intent = new Intent(CaptchaRActivity.this, RegisterActivity.class);
                            startActivity(intent);
                        } else {
                            runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "异常,重新尝试", Toast.LENGTH_SHORT).show());
                            Intent intent = new Intent(CaptchaRActivity.this, RegisterActivity.class);
                            startActivity(intent);
                        }
                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(CaptchaRActivity.this, "连接失败", Toast.LENGTH_SHORT).show());
                        Intent intent = new Intent(CaptchaRActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                }).start();
                return "验证通过";
            }

            @Override
            public String onFailed(int count) {
                Toast.makeText(CaptchaRActivity.this, "验证失败,失败次数" + count, Toast.LENGTH_SHORT).show();
                return "验证失败";
            }

            @Override
            public String onMaxFailed() {
                Toast.makeText(CaptchaRActivity.this, "验证超过次数，重新注册", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(CaptchaRActivity.this,RegisterActivity.class);
                startActivity(intent);
                return "重新登录";
            }
        });
    }
}
